package com.youi.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youi.shop.commons.exceptions.GlobalException;
import com.youi.shop.commons.result.RespEntity;
import com.youi.shop.commons.result.StatusCode;
import com.youi.shop.mapper.MemberMapper;
import com.youi.shop.pojo.entity.Member;
import com.youi.shop.pojo.qo.member.MemberLoginParams;
import com.youi.shop.pojo.qo.member.MemberRegisterParams;
import com.youi.shop.pojo.vo.member.MemberVO;
import com.youi.shop.service.MemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author xxf
 * @since 2020-11-09
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Resource
    MemberMapper memberMapper;

    /**
     * 通过用户名查询member对象校验密码
     *
     * @param params
     * @return
     */
    @Override
    public RespEntity<MemberVO> selectOne(MemberLoginParams params) {
        //查询数据库
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("username", params.getUsername())
                .eq("status", 0);
        //返回查询结果
        Member member = memberMapper.selectOne(wrapper);
        MemberVO memberVO = new MemberVO();
        RespEntity<MemberVO> respEntity = null;

        if (member == null) {
            //查询不到用户名返回错误结果消息
            respEntity = RespEntity.error(StatusCode.USERNAME_UNMATCHED_ERROR);

        } else {
            //校验密码
            if (params.getPassword().equals(member.getPassword())) {
                BeanUtils.copyProperties(member, memberVO);
                respEntity = RespEntity.success(memberVO);
            } else {
                //密码错误
                respEntity = RespEntity.error(StatusCode.LOGIN_ERROR);
            }

        }
        return respEntity;
    }

    /**
     * 添加一个会员
     * @param params
     * @return
     */
    @Override
    public boolean insert(MemberRegisterParams params) {
        //查询数据库
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("username", params.getUsername())
                .eq("status", 0);
        //返回查询结果
        Member member = memberMapper.selectOne(wrapper);
        boolean flag = false;
        //member不为空 已经有同名用户
        if (member != null && params.getUsername().equals(member.getUsername())) {
            //用户已存在
            throw new GlobalException(StatusCode.REGISTER_ERROR);
        } else {
            //将会员注册信息存入数据库
            member = new Member();
            BeanUtils.copyProperties(params, member);
            //保存成功 返回true
            int res = memberMapper.insert(member);
            if (res > 0) {
                flag = true;
            }
        }


        return flag;
    }
}
